package com.ruoyi.pdf.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.pdf.service.IRecognizePdfService;
import org.springframework.stereotype.Service;
//import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

@Service
public class RecognizePdfServiceImpl implements IRecognizePdfService {

    @Override
    public JSONArray recognizePdf(String url , String base64Pdf) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("base64", base64Pdf);
        String paramJson = JSON.toJSONString(jsonObject);
        String recogJson = this.getOCR(url, paramJson);
        JSONObject jsonRet = JSON.parseObject(recogJson);
        return jsonRet.getJSONArray("parse result");
    }


    private String getOCR(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(30000);
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setRequestProperty("accept", "json");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
            out.println(param);
            out.flush();
            if (conn.getResponseCode() == 200) {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } else {
                System.err.println("发送 POST 请求出现异常！" + conn.getResponseCode());
                in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "utf-8"));
                String error = "";
                String line;
                while ((line = in.readLine()) != null) {
                    error += line;
                }
                System.err.println(error);
            }
        } catch (Exception e) {
            System.err.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
            throw new ServiceException("文件解析失败") ;
        }
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

    @Override
    public String encodeBase64(File file) {
        try{
            if(!file.exists() || file.isDirectory()){
                System.err.println("File not exists. " + file);
                return null;
            }
            FileInputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int)file.length()];
            inputFile.read(buffer);
            inputFile.close();
            return new String(Base64.getEncoder().encode(buffer));
            //return new BASE64Encoder().encode(buffer);
        } catch (Exception e) {
            System.err.println("Base64 转换异常！"+e);
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String encodeBase64(byte[] bytes) {
        try{
            return new String(Base64.getEncoder().encode(bytes));
           //return new BASE64Encoder().encode(bytes);
        } catch (Exception e) {
            System.err.println("Base64 转换异常！"+e);
            e.printStackTrace();
            return null;
        }
    }
}
